import React from 'react';
import PropTypes from 'prop-types';
import { Modal, message } from 'antd';
import Utils from '../common/Utils';

export default class BaseDialog extends React.Component {

    static propTypes = {
        modalProps: PropTypes.object
    }

    state = {
        data: null,
    };

    getModalProps() {
        return this.props.modalProps || this.state.modalProps || {};
    }

    resolve = Utils.noop;

    render() {
        return <Modal
            visible={this.state.data != null}
            onOk={this.onOk.bind(this)}
            onCancel={this.onCancel.bind(this)}
            {...this.getModalProps()}
        >
            {this.state.data ? this.renderContent(this.state.data) : <div className='hide' />}
        </Modal>;
    }

    onResult() {
        return this.state.data;
    }


    async getData() {
        if (this.form) {
            return new Promise((resolve, reject) => {
                let form = this.form;
                while (form.getForm) {
                    form = form.getForm();
                }
                return form.validateFields((err, values) => {
                    if (err) {
                        reject(err);
                    } else {
                        form.resetFields();
                        resolve(values);
                    }
                });
            });
        }
        return this.state.data;
    }

    onOk() {
        this.getData(this.state.data, this)
            .then(data => {
                this.setState({ data: null });                
                this.resolve({ status: 'ok', data });
            }).catch(err => {
                message.error('提交失败:' + err);
                //this.resolve({ status: 'error', data: err });
            });
    }

    onCancel() {
        this.setState({ data: null });
        this.resolve({ status: 'cancel' });
    }

    async show(data) {
        this.setState({ data });

        return new Promise(resolve => {
            this.resolve = resolve;
        });
    }
}